// 游戏状态和变量
const gameState = {
    score: 0,
    lives: 3,
    level: 1,
    isGameRunning: false,
    playerSpeed: 5,
    obstacleSpeed: 3,
    coinSpeed: 2,
    spawnRate: 2000, // 障碍物生成间隔（毫秒）
    coinRate: 3000,  // 金币生成间隔（毫秒）
    keys: {
        left: false,
        right: false,
        up: false,
        down: false
    },
    timers: {
        obstacle: null,
        coin: null,
        gameLoop: null
    }
};

// DOM元素
const elements = {
    startScreen: document.getElementById('game-start'),
    gameContainer: document.getElementById('game-container'),
    gameOverScreen: document.getElementById('game-over'),
    gameArea: document.getElementById('game-area'),
    player: document.getElementById('player'),
    scoreDisplay: document.getElementById('score'),
    finalScoreDisplay: document.getElementById('final-score'),
    levelDisplay: document.getElementById('level'),
    startButton: document.getElementById('start-button'),
    restartButton: document.getElementById('restart-button'),
    hearts: document.querySelectorAll('.heart')
};

// 游戏区域尺寸
let gameAreaRect = null;
let playerRect = null;

// 初始化游戏
function initGame() {
    // 绑定事件监听器
    elements.startButton.addEventListener('click', startGame);
    elements.restartButton.addEventListener('click', restartGame);
    
    // 键盘控制
    document.addEventListener('keydown', handleKeyDown);
    document.addEventListener('keyup', handleKeyUp);
    
    // 触摸控制（移动设备）
    elements.gameArea.addEventListener('touchstart', handleTouchStart);
    elements.gameArea.addEventListener('touchmove', handleTouchMove, { passive: false });
    elements.gameArea.addEventListener('touchend', handleTouchEnd);
    
    // 获取游戏区域尺寸
    updateGameDimensions();
    window.addEventListener('resize', updateGameDimensions);
}

// 更新游戏区域尺寸
function updateGameDimensions() {
    gameAreaRect = elements.gameArea.getBoundingClientRect();
    playerRect = elements.player.getBoundingClientRect();
    
    // 重置玩家位置
    if (!gameState.isGameRunning) {
        elements.player.style.left = `${gameAreaRect.width / 2 - playerRect.width / 2}px`;
        elements.player.style.bottom = '20px';
    }
}

// 开始游戏
function startGame() {
    // 重置游戏状态
    resetGameState();
    
    // 更新显示
    updateScore();
    updateLives();
    updateLevel();
    
    // 切换屏幕
    elements.startScreen.classList.add('hidden');
    elements.gameContainer.classList.remove('hidden');
    elements.gameOverScreen.classList.add('hidden');
    
    // 设置游戏为运行状态
    gameState.isGameRunning = true;
    
    // 开始生成障碍物和金币
    startSpawners();
    
    // 开始游戏主循环
    gameState.timers.gameLoop = setInterval(gameLoop, 16); // 约60FPS
}

// 重置游戏状态
function resetGameState() {
    gameState.score = 0;
    gameState.lives = 3;
    gameState.level = 1;
    gameState.playerSpeed = 5;
    gameState.obstacleSpeed = 3;
    gameState.coinSpeed = 2;
    gameState.spawnRate = 2000;
    gameState.coinRate = 3000;
    
    // 清除所有游戏元素
    const obstacles = document.querySelectorAll('.obstacle');
    const coins = document.querySelectorAll('.coin');
    obstacles.forEach(obstacle => obstacle.remove());
    coins.forEach(coin => coin.remove());
    
    // 重置玩家位置
    elements.player.style.left = `${gameAreaRect.width / 2 - playerRect.width / 2}px`;
    elements.player.style.bottom = '20px';
}

// 开始生成器
function startSpawners() {
    // 清除现有的定时器
    if (gameState.timers.obstacle) clearInterval(gameState.timers.obstacle);
    if (gameState.timers.coin) clearInterval(gameState.timers.coin);
    
    // 生成障碍物
    gameState.timers.obstacle = setInterval(spawnObstacle, gameState.spawnRate);
    
    // 生成金币
    gameState.timers.coin = setInterval(spawnCoin, gameState.coinRate);
    
    // 初始生成一些金币
    setTimeout(() => {
        for (let i = 0; i < 3; i++) {
            spawnCoin();
        }
    }, 500);
}

// 生成障碍物
function spawnObstacle() {
    if (!gameState.isGameRunning) return;
    
    const obstacle = document.createElement('div');
    obstacle.classList.add('obstacle');
    
    // 随机大小和位置
    const width = Math.random() * 60 + 30; // 30-90px
    const height = Math.random() * 40 + 20; // 20-60px
    const left = Math.random() * (gameAreaRect.width - width);
    
    obstacle.style.width = `${width}px`;
    obstacle.style.height = `${height}px`;
    obstacle.style.left = `${left}px`;
    obstacle.style.top = '-50px'; // 从屏幕上方外部进入
    
    elements.gameArea.appendChild(obstacle);
    
    // 移动障碍物
    const moveInterval = setInterval(() => {
        if (!gameState.isGameRunning) {
            clearInterval(moveInterval);
            return;
        }
        
        const currentTop = parseFloat(obstacle.style.top) || 0;
        obstacle.style.top = `${currentTop + gameState.obstacleSpeed}px`;
        
        // 检查是否超出屏幕底部
        if (currentTop > gameAreaRect.height) {
            clearInterval(moveInterval);
            obstacle.remove();
        }
        
        // 碰撞检测
        if (checkCollision(elements.player, obstacle)) {
            clearInterval(moveInterval);
            obstacle.remove();
            loseLife();
        }
    }, 16);
}

// 生成金币
function spawnCoin() {
    if (!gameState.isGameRunning) return;
    
    const coin = document.createElement('div');
    coin.classList.add('coin');
    
    // 随机位置
    const left = Math.random() * (gameAreaRect.width - 20); // 20是金币的宽度
    
    coin.style.left = `${left}px`;
    coin.style.top = '-30px'; // 从屏幕上方外部进入
    
    elements.gameArea.appendChild(coin);
    
    // 移动金币
    const moveInterval = setInterval(() => {
        if (!gameState.isGameRunning) {
            clearInterval(moveInterval);
            return;
        }
        
        const currentTop = parseFloat(coin.style.top) || 0;
        coin.style.top = `${currentTop + gameState.coinSpeed}px`;
        
        // 检查是否超出屏幕底部
        if (currentTop > gameAreaRect.height) {
            clearInterval(moveInterval);
            coin.remove();
        }
        
        // 碰撞检测（收集金币）
        if (checkCollision(elements.player, coin)) {
            clearInterval(moveInterval);
            coin.remove();
            collectCoin();
        }
    }, 16);
}

// 收集金币
function collectCoin() {
    gameState.score += 10;
    updateScore();
    
    // 每收集5个金币升级
    if (gameState.score % 50 === 0) {
        levelUp();
    }
    
    // 添加收集动画效果
    const coinSound = new Audio(); // 可以添加金币收集音效
    try {
        coinSound.play();
    } catch (e) {
        // 忽略音频播放错误
    }
}

// 升级
function levelUp() {
    gameState.level++;
    updateLevel();
    
    // 增加游戏难度
    gameState.obstacleSpeed += 0.5;
    gameState.coinSpeed += 0.3;
    gameState.spawnRate = Math.max(500, gameState.spawnRate - 150); // 最小间隔500ms
    
    // 重新启动生成器以应用新的生成速率
    startSpawners();
}

// 失去生命值
function loseLife() {
    gameState.lives--;
    updateLives();
    
    // 玩家闪烁效果
    elements.player.style.opacity = '0.5';
    setTimeout(() => {
        elements.player.style.opacity = '1';
    }, 300);
    
    // 检查游戏是否结束
    if (gameState.lives <= 0) {
        endGame();
    }
}

// 结束游戏
function endGame() {
    gameState.isGameRunning = false;
    
    // 清除定时器
    if (gameState.timers.gameLoop) clearInterval(gameState.timers.gameLoop);
    if (gameState.timers.obstacle) clearInterval(gameState.timers.obstacle);
    if (gameState.timers.coin) clearInterval(gameState.timers.coin);
    
    // 更新最终分数
    elements.finalScoreDisplay.textContent = gameState.score;
    
    // 切换屏幕
    elements.gameContainer.classList.add('hidden');
    elements.gameOverScreen.classList.remove('hidden');
}

// 重新开始游戏
function restartGame() {
    startGame();
}

// 游戏主循环
function gameLoop() {
    if (!gameState.isGameRunning) return;
    
    movePlayer();
}

// 移动玩家
function movePlayer() {
    const currentLeft = parseFloat(elements.player.style.left) || 0;
    const currentBottom = parseFloat(elements.player.style.bottom) || 20;
    
    let newLeft = currentLeft;
    let newBottom = currentBottom;
    
    // 根据按键状态移动
    if (gameState.keys.left && newLeft > 0) {
        newLeft -= gameState.playerSpeed;
    }
    if (gameState.keys.right && newLeft < gameAreaRect.width - playerRect.width) {
        newLeft += gameState.playerSpeed;
    }
    if (gameState.keys.up && newBottom < gameAreaRect.height - playerRect.height) {
        newBottom += gameState.playerSpeed;
    }
    if (gameState.keys.down && newBottom > 0) {
        newBottom -= gameState.playerSpeed;
    }
    
    // 更新位置
    elements.player.style.left = `${newLeft}px`;
    elements.player.style.bottom = `${newBottom}px`;
}

// 键盘按下事件
function handleKeyDown(event) {
    switch (event.key) {
        case 'ArrowLeft':
        case 'a':
        case 'A':
            gameState.keys.left = true;
            break;
        case 'ArrowRight':
        case 'd':
        case 'D':
            gameState.keys.right = true;
            break;
        case 'ArrowUp':
        case 'w':
        case 'W':
            gameState.keys.up = true;
            break;
        case 'ArrowDown':
        case 's':
        case 'S':
            gameState.keys.down = true;
            break;
    }
}

// 键盘释放事件
function handleKeyUp(event) {
    switch (event.key) {
        case 'ArrowLeft':
        case 'a':
        case 'A':
            gameState.keys.left = false;
            break;
        case 'ArrowRight':
        case 'd':
        case 'D':
            gameState.keys.right = false;
            break;
        case 'ArrowUp':
        case 'w':
        case 'W':
            gameState.keys.up = false;
            break;
        case 'ArrowDown':
        case 's':
        case 'S':
            gameState.keys.down = false;
            break;
    }
}

// 触摸开始事件
function handleTouchStart(event) {
    handleTouchMove(event);
}

// 触摸移动事件
function handleTouchMove(event) {
    if (!gameState.isGameRunning) return;
    
    event.preventDefault(); // 防止页面滚动
    
    const touch = event.touches[0];
    const touchX = touch.clientX - gameAreaRect.left;
    const touchY = touch.clientY - gameAreaRect.top;
    const centerX = gameAreaRect.width / 2;
    const centerY = gameAreaRect.height / 2;
    
    // 根据触摸位置更新移动状态
    const threshold = 50; // 触摸阈值
    
    gameState.keys.left = touchX < centerX - threshold;
    gameState.keys.right = touchX > centerX + threshold;
    gameState.keys.up = touchY < centerY - threshold;
    gameState.keys.down = touchY > centerY + threshold;
}

// 触摸结束事件
function handleTouchEnd() {
    gameState.keys.left = false;
    gameState.keys.right = false;
    gameState.keys.up = false;
    gameState.keys.down = false;
}

// 碰撞检测
function checkCollision(element1, element2) {
    const rect1 = element1.getBoundingClientRect();
    const rect2 = element2.getBoundingClientRect();
    
    return (
        rect1.left < rect2.right &&
        rect1.right > rect2.left &&
        rect1.top < rect2.bottom &&
        rect1.bottom > rect2.top
    );
}

// 更新分数显示
function updateScore() {
    elements.scoreDisplay.textContent = gameState.score;
}

// 更新生命值显示
function updateLives() {
    elements.hearts.forEach((heart, index) => {
        heart.style.opacity = index < gameState.lives ? '1' : '0.3';
    });
}

// 更新关卡显示
function updateLevel() {
    elements.levelDisplay.textContent = gameState.level;
}

// 当页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', initGame);